'use strict'
const http = require("http");
const https = require("https");
const moment = require("moment");
const crypto = require("crypto");
const fs = require("fs");
const util = require("util");
const pah = require("path");
const logger = require("../logger");

//配置文件
const config = require("../../config/config");

module.exports.post = function (path, send_data, exheaders = null) {
    return new Promise((resolve, reject) => {
        try {
            let req_param = setReq(path, 'POST', exheaders);
            let req = http.request(req_param, (res) => {
                let responseData = [];
                res.on('data', (data) => {
                    responseData.push(data);
                }).on('error', (err) => {
                    logger.error(err)
                    reject(err);
                }).on('end', () => {
                    let response = {};
                    try {
                        let data = responseData.join('');
                        response = JSON.parse(data);
                        resolve(response);
                    } catch (err) {
                        logger.error(err)
                        reject(err);
                    }
                })
            });

            req.on('error', function (err) {
                logger.error(err)
                reject(err);
            });

            if (send_data) {
                req.write(JSON.stringify(send_data));
            }
            req.end();
        } catch (err) {
            logger.error(err)
            reject(err);
        }
    });
};

module.exports.put = function (path, send_data) {
    return new Promise((resolve, reject) => {
        try {
            let req_param = setReq(path, 'PUT');
            let req = http.request(req_param, (res) => {
                let responseData = [];
                res.on('data', (data) => {
                    responseData.push(data);
                }).on('error', (err) => {
                    logger.error(err)
                    reject(err);
                }).on('end', () => {
                    let response = {};
                    try {
                        let data = responseData.join('');
                        response = JSON.parse(data);
                        resolve(response);
                    } catch (err) {
                        logger.error(err)
                        reject(err);
                    }
                })
            });

            req.on('error', function (err) {
                logger.error(err)
                reject(err);
            });

            if (send_data) {
                req.write(JSON.stringify(send_data));
            }
            req.end();
        } catch (err) {
            logger.error(err)
            reject(err);
        }
    });
};

/**
 * 发送get请求
 * @param {string} path 路径
 * @param {json} get_params 路径参数, 可不传
 */
module.exports.get = function (path, get_params = null) {
    return new Promise((resolve, reject) => {
        try {
            if (get_params !== null && get_params !== undefined) {
                path = path + '?' + qs.stringify(get_params);
            }
            let req_param = setReq(path);
            let req = http.request(req_param, (res) => {
                let responseData = "";
                res.on('data', (data) => {
                    responseData += data;
                }).on('error', (err) => {
                    logger.error(err)
                    reject(err);
                }).on('end', () => {
                    let response = {};
                    try {
                        response = JSON.parse(responseData);
                        resolve(response);
                    } catch (err) {
                        logger.error(err)
                        reject(err);
                    }
                })
            });

            req.on('error', function (err) {
                logger.error(err)
                reject(err);
            });

            req.end();
        } catch (err) {
            logger.error(err)
            reject(err);
        }
    })
};

/**
 * delete请求
 * @param {string} path 路径
 * @param {json} del_params 路径参数,可选
 */
module.exports.delete = function (path, del_params = null) {
    return new Promise((resolve, reject) => {
        try {
            if (del_params !== null && del_params !== undefined) {
                path = path + '?' + qs.stringify(del_params);
            }
            let req_param = setReq(path, 'DELETE');
            let req = http.request(req_param, (res) => {
                let responseData = [];
                res.on('data', (data) => {
                    responseData.push(data);
                }).on('error', (err) => {
                    logger.error(err)
                    reject(err);
                }).on('end', () => {
                    let response = {};
                    try {
                        let data = responseData.join('');
                        response = JSON.parse(data);
                        resolve(response);
                    } catch (err) {
                        logger.error(err)
                        reject(err);
                    }
                })
            });

            req.on('error', function (err) {
                logger.error(err)
                reject(err);
            });

            req.end();
        } catch (err) {
            logger.error(err)
            reject(err);
        }
    })
};

module.exports.upload = function* (path, filePath) {

    const msReq = setReq(path, "POST");
    let httpRes = yield superAgent.post(`${config.api.host}:${config.api.port}${path}`)
        .set(msReq.headers)
        .attach('file', filePath);
    return httpRes.body ? httpRes.body : false;
}

function setReq(path, method = 'GET', exheaders = null) {
    var req_param = {
        host: config.api.host,
        port: config.api.port,
        path: path,
        timeout: 30000,
        method: method
    };

    //headers
    var hds = req_param.headers === undefined ? {} : req_param.headers;
    hds['Content-Type'] = 'application/json';
    var datetime = moment().format('Y-MM-DD HH:mm:ss');
    hds.datetime = datetime;
    hds.appkey = config.api.appkey;
    hds.sign = crypto.createHash('md5').update(config.api.appkey + config.api.token + datetime).digest('hex').toUpperCase();

    req_param.headers = hds;

    return req_param;
}


